package org.raymond.iworks.study.netty.atguigu.netty.groupchat;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.net.InetSocketAddress;
import java.util.Scanner;

/**
 * @author raymond
 * @version V1.0
 * @Description: TODO
 */
public class GroupChatClient {
    private int port;

    public GroupChatClient(int port){
        this.port = port;
    }
    public void run() throws Exception {
        EventLoopGroup workGroup = new NioEventLoopGroup();

        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(workGroup)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new StringDecoder())
                                    .addLast(new StringEncoder())
                                    .addLast(new GroupChatClientHandler());
                        }
                    });

            ChannelFuture cf = bootstrap.connect(new InetSocketAddress(port)).sync();
            // cf.channel().closeFuture().sync();
            Channel channel = cf.channel();
            Scanner scanner = new Scanner(System.in);
            while(scanner.hasNext()){
                String line = scanner.nextLine();
                channel.writeAndFlush(line);
            }
        } finally {
            workGroup.shutdownGracefully();
        }
    }
    public static void main(String[] args) throws Exception {
        new GroupChatClient(6666).run();
    }
}
